package com.code.zjm.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.code.zjm.R;
import com.code.zjm.entity.User;
import com.code.zjm.helper.DBHelper;

import java.util.ArrayList;

/**
 * Created by ZJM on 2017/5/4.
 */

public class DetailActivity extends AppCompatActivity {
    private int mResultCode;
    private TextView editUser, shareUser, deleteUser, phoneNumber;
    private ImageView sendEmail;
    private LinearLayout call;
    private User user;
    private int position;
    private String[] callData;
    private String status;
    private View numChooseView;

    //号码选择的对话框
    private AlertDialog numChooseDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        //ActionBar 设置
        //其中 getSupportActionBar 方法不带参数时获取 ActionBar 对象
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //图标导航的功能，即在 ActionBar 显示返回图标
            actionBar.setDisplayHomeAsUpEnabled(true);
            //设置 返回图标此处在 style.xml 文件的相关主题中设置了
//            actionBar.setHomeAsUpIndicator(R.drawable.back);
        }

        initData();
        initView();
        initListener();
        setTitle(user.getUsername());
    }

    private void initData() {
        user = getIntent().getParcelableExtra("user");
        position = getIntent().getIntExtra("position", 0);
    }

    private void initView() {
        call = (LinearLayout) findViewById(R.id.lv_phone);
        sendEmail = (ImageView) findViewById(R.id.iv_send_email);
        editUser = (TextView) findViewById(R.id.tv_edit_user);
        shareUser = (TextView) findViewById(R.id.tv_share_user);
        deleteUser = (TextView) findViewById(R.id.tv_delete_user);
        phoneNumber = (TextView) findViewById(R.id.phone_number);
        phoneNumber.setText(user.getMobilePhone());
    }


    private void initListener() {

        //拨打电话
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status = Intent.ACTION_CALL;
                if (callData == null) {
                    //加载可用的号码
                    loadAvailableCallData();
                }

                if (callData.length == 0) {
                    //提示没有可用的号码
                    Toast.makeText(DetailActivity.this, "没有可用的号码！", Toast.LENGTH_LONG).show();
                } else if (callData.length == 1) {
                    //如果之有一个可用的号码，这直接使用这个号码拨出
                    Intent intent =
                            new Intent(Intent.ACTION_CALL, Uri.parse("tel://" + callData[0]));
                    if (ActivityCompat.checkSelfPermission(DetailActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    startActivity(intent);
                } else {
                    //如果有2个或者2个以上号码，弹出号码选择对话框
                    initNumChooseDialog();
                }
            }
        });

        //发送邮件
        sendEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                status = Intent.ACTION_SENDTO;
                if (callData == null) {
                    loadAvailableCallData();
                }
                if (callData.length == 0) {
                    //提示没有可用的号码
                    Toast.makeText(DetailActivity.this, "没有可用的号码！", Toast.LENGTH_LONG).show();
                } else if (callData.length == 1) {
                    //如果之后又一个可用的号码，这直接使用这个号码拨出
                    Intent intent =
                            new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + callData[0]));
                    startActivity(intent);
                } else {
                    initNumChooseDialog();
                }
            }
        });

        //编辑邮件
        editUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DetailActivity.this, EditUserActivity.class);
                intent.putExtra("user", user);
                startActivityForResult(intent, position);
            }
        });

        //分享联系人
        shareUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(DetailActivity.this, "You click the share user item", Toast.LENGTH_SHORT).show();
            }
        });

        //删除联系人
        deleteUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(DetailActivity.this)
                        .setTitle("确定要删除当前联系人吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DBHelper helper = new DBHelper(DetailActivity.this);
                                helper.openDatabase();
                                helper.delete(user.get_id());
                                setResult(4);
                                finish();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();

            }
        });
    }

    /**
     * 装载可用的号码
     */
    public void loadAvailableCallData() {
        ArrayList<String> callNums = new ArrayList<>();
        if (!user.getMobilePhone().equals("")) {
            callNums.add(user.getMobilePhone());
        }
        if (!user.getFamilyPhone().equals("")) {
            callNums.add(user.getFamilyPhone());
        }

        if (!user.getOfficePhone().equals("")) {
            callNums.add(user.getOfficePhone());
        }


        callData = new String[callNums.size()];

        for (int i = 0; i < callNums.size(); i++) {
            callData[i] = callNums.get(i);
        }

    }

    /**
     * 号码选择框
     */
    public void initNumChooseDialog() {
        if (numChooseDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            LayoutInflater inflater = LayoutInflater.from(this);
            numChooseView = inflater.inflate(R.layout.numchoose, null);
            ListView lv = (ListView) numChooseView.findViewById(R.id.num_list);
            ArrayAdapter array =
                    new ArrayAdapter(this, android.R.layout.simple_list_item_1, callData);
            lv.setAdapter(array);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                        long arg3) {
                    String num = String.valueOf(arg0.getItemAtPosition(arg2));
                    Intent intent = null;
                    if (status.equals(Intent.ACTION_CALL)) {
                        intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel://" + num));
                    } else {
                        intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + num));
                    }

                    startActivity(intent);
                    //对话框消失
                    numChooseDialog.dismiss();
                }
            });


            builder.setView(numChooseView);
            numChooseDialog = builder.create();

        }
        numChooseDialog.show();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home://对应 ActionBar 的返回图标
                setResult(mResultCode);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mResultCode = resultCode;
    }
}
